package com.ljx.qqpro.service.impl;

import com.ljx.qqpro.dto.chat.ChatCell;
import com.ljx.qqpro.entity.ChatUserEntity;
import com.ljx.qqpro.entity.UserEntity;
import com.ljx.qqpro.service.ChatUserService;
import com.ljx.qqpro.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.qqpro.common.utils.PageUtil;
import com.ljx.qqpro.common.utils.Query;

import com.ljx.qqpro.dao.ChatDao;
import com.ljx.qqpro.entity.ChatEntity;
import com.ljx.qqpro.service.ChatService;


@Service("chatService")
public class ChatServiceImpl extends ServiceImpl<ChatDao, ChatEntity> implements ChatService {

    @Autowired
    private UserService userService;

    @Autowired
    private ChatUserService chatUserService;

    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<ChatEntity> page = this.page(
                new Query<ChatEntity>().getPage(params),
                new QueryWrapper<ChatEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public List<ChatCell> getUserChat(Long userId) {

        List<ChatCell> chatCellList = chatUserService.queryChatList(userId);

        return chatCellList.stream().map(chatCellEntity -> {
            // 查询是私聊还是群聊，私聊就用头像，群聊就用设置的封面
            if (StringUtils.isEmpty(chatCellEntity.getCoverImage())) {
                UserEntity userEntity;
                if (!userId.equals(chatCellEntity.getCreaterId()))
                    userEntity = userService.getById(chatCellEntity.getCreaterId());
                else userEntity = userService.getById(chatCellEntity.getToUser());
                chatCellEntity.setCoverImage(userEntity.getAvatar());
                chatCellEntity.setNickname(userEntity.getNickname());
            }
            return chatCellEntity;
        }).collect(Collectors.toList());
    }
}